package com.itheima.dao;

import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.UserService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.InterProcessLockUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @author leboy
 * @description
 */
@Slf4j
public class ThreadToDo implements Runnable {
	@Autowired
	private OrderDao orderDao;

	@Autowired
	private OrderSettingDao orderSettingDao;

	// 模拟会员id
	private int memberId = 1000;

	// 数量统计
	public static int count=0;

	private static int num = 0;

	private static InterProcessMutex lock;
	static {
		// 每一秒重试一次  重试15次
		RetryPolicy retryPolicy = new RetryNTimes(15,1000 );
		// client
		CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);
		// 启动客户端
		client.start();
		// 构造锁
		lock = new InterProcessMutex(client, "/serviceLock");
		lock = InterProcessLockUtils.getLock();
	}
	/**
	 * 2020-7-15 的orderSetting的 预约数量自增1
	 */
	private void orderSettingIncrement() {
		// 以七月十五那天预约进行测试
		Date date = DateUtils.parseString2Date("2020-7-15");
		OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);//根据日期查询预约设置信息
		if(orderSetting.getReservations() >= orderSetting.getNumber()){
			//所选日期已经约满，无法预约
			throw new RuntimeException("预约人数已满！！！");
		}
		orderSetting.setReservations(orderSetting.getReservations() + 1);
		orderSettingDao.editReservationsByOrderDate(orderSetting);
	}

	/**
	 * 2020-7-15 order 增加一条预约
	 */
	private void orderIncrement(){
		//预约信息
//		setmeal_id定为12
//		date 定为 2020-7-15
		Date date = DateUtils.parseString2Date("2020-7-15");
		// 模拟不同会员id
		int memberId = 1;
		Order order = new Order(12,date, "微信预约", Order.ORDERSTATUS_NO,memberId);
		orderDao.add(order);
	}


	@Override
	public void run(){


		while (true) {

			try {
				lock.acquire();
	     		/*orderSettingIncrement();
				orderIncrement();*/
				//************************************************
				if (num>=10){
					log.debug("*************即将break,此时num的值："+num);
					break;
				}
				// 睡一下
				Thread.sleep(1000);

				num++;
				count++;
				//************************************************
				log.debug(Thread.currentThread().getName() + "：***********此线程执行了一次,num为：" + num);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
						lock.release();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}

	}
}
